{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "eager_basics.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "private_outputs": true,
      "collapsed_sections": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "iPpI7RaYoZuE"
      },
      "source": [
        "##### Copyright 2018 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "form",
        "colab_type": "code",
        "id": "hro2InpHobKk",
        "colab": {}
      },
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "U9i2Dsh-ziXr"
      },
      "source": [
        "# Eager modunun ana hatlari"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Hndw-YcxoOJK"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/docs/blob/master/site/tr/r1/tutorials/eager/eager_basics.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/docs/blob/master/site/tr/r1/tutorials/eager/eager_basics.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "6sILUVbHoSgH"
      },
      "source": [
        "Bu kitapcikta TensorFlow kullanarak konuya giris yapacagiz. Asagidaki konulari isleyecegiz:\n",
        "\n",
        "* Gerekli paketleri iceri aktarma\n",
        "* Tensorlari olusturma ve kullanma\n",
        "* GPU hizlandirmayi kullanmak\n",
        "* Veri setleri"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "z1JcS5iBXMRO"
      },
      "source": [
        "## TensorFlow'u iceri alalim\n",
        "\n",
        "'tensorflow' modulunu iceri alalim ver eager modunu secelim.\n",
        "Eager modu, TensorFlow'a detaylarini daha sonra aciklayacagimiz etkilesimli bir arayuz saglar."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "code",
        "colab_type": "code",
        "id": "RlIWhyeLoYnG",
        "colab": {}
      },
      "source": [
        "from __future__ import absolute_import, division, print_function\n",
        "\n",
        "import tensorflow as tf\n",
        "\n",
        "tf.enable_eager_execution()"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "H9UySOPLXdaw"
      },
      "source": [
        "## Tensorlar\n",
        "\n",
        "Tensor kisaca cok boyutlu bir dizidir. NumPy'deki 'ndarray' nesneleri gibi, `Tensor` nesnesinin de bir veri turu ve sekli vardir. Ayrica Tensorlar GPU gibi hizlandirilmis hafizada bulunabilirler. TensorFlow, Tensorlari olusturmak ve kullanmak icin zengin islemlere sahiptir ([tf.add](https://www.tensorflow.org/api_docs/python/tf/add), [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/matmul), [tf.linalg.inv](https://www.tensorflow.org/api_docs/python/tf/linalg/inv) etc.). Bu islemler Python tiplerini otomatik olarak degistirirler. Ornegin:\n"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "code",
        "colab_type": "code",
        "id": "ngUe237Wt48W",
        "colab": {}
      },
      "source": [
        "print(tf.add(1, 2))\n",
        "print(tf.add([1, 2], [3, 4]))\n",
        "print(tf.square(5))\n",
        "print(tf.reduce_sum([1, 2, 3]))\n",
        "print(tf.encode_base64(\"hello world\"))\n",
        "\n",
        "# Islec asiri yuklenmesi de desteklenir\n",
        "print(tf.square(2) + tf.square(3))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "IDY4WsYRhP81"
      },
      "source": [
        "Her Tensor'un bir sekli ve veri turu vardir"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "srYWH1MdJNG7",
        "colab": {}
      },
      "source": [
        "x = tf.matmul([[1]], [[2, 3]])\n",
        "print(x.shape)\n",
        "print(x.dtype)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "eBPw8e8vrsom"
      },
      "source": [
        "NumPy dizileri ve TensorFlow Tensorlari arasindaki en belirgin farklar sunlardir:\n",
        "\n",
        "1. Tensorlar hizlandirilmis hafizalar tarafindan desteklenebilr (GPU, TPU gibi).\n",
        "2. Tensorlar degistirilemez."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Dwi1tdW3JBw6"
      },
      "source": [
        "### NumPy Uyumlulugu\n",
        "\n",
        "TensorFlow Tensorlari ile NumPy 'ndarray'leri arasindaki donusum cok basittir:\n",
        "\n",
        "* TensorFlow islemleri otomatik olarak NumPy ndarray'lerini Tensorlara donusturur.\n",
        "* NumPy islemleri de otomatik olarak Tensorlari NumPy ndarray'lerine donusturur.\n",
        "\n",
        "'.numpy()' metodunu kullanarak Tensorlari belirgin sekilde NumPy ndarray'lerine donusturebilirsiniz.\n",
        "Tensorlar ve 'ndarray'ler temelde mumkun oldugunca ayni sekilde tanimlandigi icin bu donusturmeler ucuzdur. Fakat, NumPy dizileri her zaman ana hafizada calisirken Tensorlar GPU hafizasini da kullanabildigi icin her zaman benzer sekilde tanimlanamazlar ve donusturme isleminde GPU'dan ana hafizaya kopyalama da bulunur."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "lCUWzso6mbqR",
        "colab": {}
      },
      "source": [
        "import numpy as np\n",
        "\n",
        "ndarray = np.ones([3, 3])\n",
        "\n",
        "print(\"TensorFlow operations convert numpy arrays to Tensors automatically\")\n",
        "tensor = tf.multiply(ndarray, 42)\n",
        "print(tensor)\n",
        "\n",
        "\n",
        "print(\"And NumPy operations convert Tensors to numpy arrays automatically\")\n",
        "print(np.add(tensor, 1))\n",
        "\n",
        "print(\"The .numpy() method explicitly converts a Tensor to a numpy array\")\n",
        "print(tensor.numpy())"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "PBNP8yTRfu_X"
      },
      "source": [
        "## GPU hizlandirmasi\n",
        "\n",
        "Hesaplamalar icin GPU kullanarak bircok TensorFlow islemleri hizlandirilabilir. TensorFlow bir islem icin, ek aciklamaya gerek duymadan, otomatik olarak GPU ya da CPU kullanimina karar verir (ve gerektiginde tensorlari GPU ve CPU hafizalarina kopyalar). Bir islem sonucu olusan tensorlar o islem hangi hafizada yurutulduyse o hafizaya kopyalanir. Ornegin:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "cellView": "code",
        "colab_type": "code",
        "id": "3Twf_Rw-gQFM",
        "colab": {}
      },
      "source": [
        "x = tf.random_uniform([3, 3])\n",
        "\n",
        "print(\"Is there a GPU available: \"),\n",
        "print(tf.test.is_gpu_available())\n",
        "\n",
        "print(\"Is the Tensor on GPU #0:  \"),\n",
        "print(x.device.endswith('GPU:0'))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "vpgYzgVXW2Ud"
      },
      "source": [
        "### Aygit Isimleri\n",
        "\n",
        "`Tensor.device` ozelligi tensorlarin bulundugu aygitin tam adini dizgi olarak temin eder. Bu dizgide bircok detay bulunmaktadir: programin calistigi anasistemin bulundugu agin taniticisi ve anasistemdeki aygit. Bunlar TensorFlow programlarinin dagitiminda gerekli olan bilgilerdir. Eger tensor sistemdeki 'N'inci GPU'ya yerlestirilmisse bu dizgi `GPU:<N>` ile biter."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ZWZQCimzuqyP"
      },
      "source": [
        "\n",
        "\n",
        "### Belirtilmis Aygit Yerlestirilmesi\n",
        "\n",
        "TensorFlow'da \"yerlestirme\" terimi islemlerin uygulama sirasinda sistemde tek tek nasil atandigi (yerlestirildigi) anlaminda kullanilmistir. Yukarida da bahsettigimiz gibi, eger ozellikle belirtilmemisse TensorFlow bir islemi nerde calistiracagina otomatik olarak karar verir ve gerekirse tensorlari oraya kopyalar. Fakat, TensorFlow islemleri 'tf.device' baglam yoneticisi kullanilarak belirli aygitlara yerlestirilebilir. Ornegin:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "RjkNZTuauy-Q",
        "colab": {}
      },
      "source": [
        "import time\n",
        "\n",
        "def time_matmul(x):\n",
        "  start = time.time()\n",
        "  for loop in range(10):\n",
        "    tf.matmul(x, x)\n",
        "\n",
        "  result = time.time()-start\n",
        "\n",
        "  print(\"10 loops: {:0.2f}ms\".format(1000*result))\n",
        "\n",
        "\n",
        "# CPU ustunde zorla calistirma\n",
        "print(\"On CPU:\")\n",
        "with tf.device(\"CPU:0\"):\n",
        "  x = tf.random_uniform([1000, 1000])\n",
        "  assert x.device.endswith(\"CPU:0\")\n",
        "  time_matmul(x)\n",
        "\n",
        "# Eger mumkunse GPU ustunde zorla calistirma #0\n",
        "if tf.test.is_gpu_available():\n",
        "  with tf.device(\"GPU:0\"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.\n",
        "    x = tf.random_uniform([1000, 1000])\n",
        "    assert x.device.endswith(\"GPU:0\")\n",
        "    time_matmul(x)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "o1K4dlhhHtQj"
      },
      "source": [
        "## Veri setleri\n",
        "\n",
        "Simdi modelimize veri akimini saglamak icin [`tf.data.Dataset` API](https://www.tensorflow.org/r1/guide/datasets)'sini nasil kullanacagimizi gorecegiz:\n",
        "\n",
        "* `Dataset`i olusturalim.\n",
        "* Eager modunda `Dataset`in yinelenmesi.\n",
        "\n",
        "Modelimizin egitim ve degerlendirme dongulerine verilen kompleks girdi hatlarini 'Dataset' API'si ile basit ve tekrar kullanilabilir parcalardan olusturmanizi tavsiye ederiz.\n",
        "\n",
        "'Dataset' nesnesi olusturma API'si eager modunda iken TensorFlow graph'taki ile aynidir, fakat veri setindeki elemanlarin yinelenmesi islemi biraz daha basittir.\n",
        "'tf.data.Dataset' nesnesi ustunde direk olarak Python yinelemesi yapabildiginiz icin `tf.data.Iterator` nesnesi olusturmaniza gerek yoktur.\n",
        "Sonuc olarak, eger eager modunu kullaniyorsaniz, [TensorFlow Rehberi](https://www.tensorflow.org/r1/guide/datasets)'nde anlatilan yineleme gereksizdir."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "zI0fmOynH-Ne"
      },
      "source": [
        "### `Dataset` kaynagi olusturalim\n",
        "\n",
        "Buradaki fonksiyonlardan birini [`Dataset.from_tensors`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensors), [`Dataset.from_tensor_slices`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices) ya da kutuklerden okunan nesneleri [`TextLineDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) veya [`TFRecordDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset) kullanarak _source_ dataset olusturabiliriz. [TensorFlow Rehberi](https://www.tensorflow.org/r1/guide/datasets#reading_input_data)'nde daha detayli bilgi bulabilirsiniz."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "F04fVOHQIBiG",
        "colab": {}
      },
      "source": [
        "ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])\n",
        "\n",
        "# CSV kutugunu olusturalim\n",
        "import tempfile\n",
        "_, filename = tempfile.mkstemp()\n",
        "\n",
        "with open(filename, 'w') as f:\n",
        "  f.write(\"\"\"Line 1\n",
        "Line 2\n",
        "Line 3\n",
        "  \"\"\")\n",
        "\n",
        "ds_file = tf.data.TextLineDataset(filename)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "vbxIhC-5IPdf"
      },
      "source": [
        "### Transformations (donusumler) uygulayalim\n",
        "\n",
        "Veri seti kayitlarini donusturmek icin transformations (donusumler) fonksiyonlarini kullanabiliriz: ornegin [`map`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map), [`batch`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#batch), [`shuffle`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle). `tf.data.Dataset` API dokumanlari hakkinda daha fazla bilgi icin [buraya bakiniz](https://www.tensorflow.org/api_docs/python/tf/data/Dataset)."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "uXSDZWE-ISsd",
        "colab": {}
      },
      "source": [
        "ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)\n",
        "\n",
        "ds_file = ds_file.batch(2)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "A8X1GNfoIZKJ"
      },
      "source": [
        "### Yineleme\n",
        "\n",
        "Eager modunda 'Dataset' nesneleri yinelemeleri destekler.\n",
        "Eger TensorFlow 'graphs'taki 'Dataset' kullanimina asina iseniz, `Dataset.make_one_shot_iterator()` ya da `get_next()` kullanimina gerek olmadigina lutfen dikkat ediniz."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ws-WKRk5Ic6-",
        "colab": {}
      },
      "source": [
        "print('Elements of ds_tensors:')\n",
        "for x in ds_tensors:\n",
        "  print(x)\n",
        "\n",
        "print('\\nElements in ds_file:')\n",
        "for x in ds_file:\n",
        "  print(x)"
      ],
      "execution_count": 0,
      "outputs": []
    }
  ]
}